<?php

namespace Home\Controller;
use Home\Logic\UsersLogic;
use Think\Controller;
use Think\AjaxPage;
use Think\Page;
use Think\Verify;

class IndexController extends Controller {


//    public function index() {
//        // 如果是手机跳转到 手机模块
//        if (true == isMobile()) {
//            header("Location: " . U('Mobile/Index/index'));
//        }
//
//        if (session('?user'))
//            header("Location: " . U('Home/User/Index'));
//        $this->display();
//    }
    /**
     *  登录
     */
    public function Index() {

       
		 // 如果是手机跳转到 手机模块
		 if (true == isMobile()) {
            header("Location: ".U('Mobile/User/Index'));
           //header("Location: " . U('Mobile/Index/index'));
       }
        if (session('?user')) {
            header("Location: " . U('Home/User/Index'));
        }
        $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U("Home/Index/index");
        $this->assign('referurl', $referurl);
        $this->web = tpCache('shop_info');
        $this->display();
    }

    public function do_login() {
        $username = I('post.username');
        $password = I('post.password');
        $username = trim($username);
        $password = trim($password);
        $verify_code = I('post.verify_code');

        $verify = new Verify();
        if (!$verify->check($verify_code, 'index_index')) {
            $res = array('status' => 0, 'msg' => '验证码错误');
            exit(json_encode($res));
        }

        $logic = new UsersLogic();
        $res = $logic->login($username, $password);

        if ($res['status'] == 1) {
            $res['url'] = urldecode(I('post.referurl'));
            session('user', $res['result']);
            setcookie('user_id', $res['result']['user_id'], null, '/');
            setcookie('is_distribut', $res['result']['is_distribut'], null, '/');
            $nickname = empty($res['result']['nickname']) ? $username : $res['result']['bank_name'];
            // $nickname = empty($res['result']['nickname']) ? $username : $res['result']['nickname'];
            setcookie('uname', urlencode($nickname), null, '/');
            setcookie('cn', 0, time() - 3600, '/');
            exit(json_encode($res));
            $logic->lastlogin($res['result']['user_id']);//登录成功后修改最后一次登录的信息
//            $cartLogic = new \Home\Logic\CartLogic();
//            $cartLogic->login_cart_handle($this->session_id, $res['result']['user_id']);  //用户登录后 需要对购物车 一些操作
        }
        exit(json_encode($res));
    }
    /**
     *  注册
     */
    public function reg() {
        if (IS_POST) {

            $logic = new UsersLogic();
            //验证码检验
            $username = I('post.username', '');
            $password = I('post.password', '');
            $password2 = I('post.password2', '');
            $verify_code = I('post.verify_code', '');
            $verify = new Verify();
            if (!$verify->check($verify_code, 'index_reg')) {
                $this->error('验证码错误');
            }
            //是否开启注册验证码机制
            if (check_mobile($username) && tpCache('sms.regis_sms_enable')) {
                $code = I('post.code', '');
                if (!$code)
                    $this->error('请输入短信验证码');
                $check_code = $logic->sms_code_verify($username, $code, $this->session_id);
                if ($check_code['status'] != 1)
                    $this->error($check_code['msg']);
            }
            $data = $logic->reg(I('post.'));
            if ($data['status'] != 1)
                $this->error($data['msg']);
            $this->success($data['msg'], U('Home/User/index'));
            exit;
        }
        $a = range(0, 9);
        for ($i = 0; $i < tpCache('reg.account_num'); $i++) {
            $b[] = array_rand($a);
        }


        $this->account = tpCache('reg.account_qz') . implode('', $b); // 自动生成会员账号 并传值
        $this->uname = encryptzf($_GET['tjr_accname'], 'D', 'zfuwl'); //解密

        $user=M('users')->where(array('account' =>$this->uname))->find();
        $upd_user=M('users')->find($user['upd_id']);
        $this->gettjraccname = $_GET['tjr_accname'];
        $this->lever = M('user_level')->field('level_id,level_name,amount')->select();
        $this->assign('regis_sms_enable', tpCache('sms.regis_sms_enable')); // 注册启用短信：
        $p = M('region')->where(array('parent_id' => 0, 'level' => 1))->select(); //地址 四级联动
        $this->assign('province', $p);
        $sms_time_out = tpCache('sms.sms_time_out') > 0 ? tpCache('sms.sms_time_out') : 120;
        $this->assign('sms_time_out', $sms_time_out); // 手机短信超时时间
        $this->assign('upd_user', $upd_user); // 手机短信超时时间
        $this->reg = tpCache('reg');
        $this->shop_info = tpCache('shop_info');
        $this->display();
    }


//    public function shop() {
//
//        // 如果是手机跳转到 手机模块
//        if (true == isMobile()) {
//            header("Location: " . U('Mobile/Index/index'));
//        }
//
//        $hot_goods = $hot_cate = $cateList = array();
//        $sql = "select a.goods_name,a.goods_id,a.shop_price,a.market_price,a.cat_id,b.parent_id_path,b.name from __PREFIX__goods as a left join ";
//        $sql .= " __PREFIX__goods_category as b on a.cat_id=b.id where a.is_hot=1 and a.is_on_sale=1 order by a.sort"; //二级分类下热卖商品
//        $index_hot_goods = M()->query($sql); //首页热卖商品
//        if ($index_hot_goods) {
//            foreach ($index_hot_goods as $val) {
//                $cat_path = explode('_', $val['parent_id_path']);
//                $hot_goods[$cat_path[1]][] = $val;
//            }
//        }
//
//        $hot_category = M('goods_category')->where("is_hot=1 and level=3 and is_show=1")->select(); //热门三级分类
//        foreach ($hot_category as $v) {
//            $cat_path = explode('_', $v['parent_id_path']);
//            $hot_cate[$cat_path[1]][] = $v;
//        }
//
//        foreach ($this->cateTrre as $k => $v) {
//            if ($v['is_hot'] == 1) {
//                $v['hot_goods'] = empty($hot_goods[$k]) ? '' : $hot_goods[$k];
//                $v['hot_cate'] = empty($hot_cate[$k]) ? '' : $hot_cate[$k];
//                $cateList[] = $v;
//            }
//        }
//
//        $this->assign('cateList', $cateList);
//        $this->display();
//    }

    /**
     *  公告详情页
     */
    public function notice() {
        $this->display();
    }

    // 二维码
    public function qr_code() {
       

         vendor("phpqrcode.phpqrcode");

            $data = I('url');
            // 纠错级别：L、M、Q、H
            $level = 'L';
            // 点的大小：1到10,用于手机端4就可以了
            $size = 4;
            // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
            $path = "images/";
            // 生成的文件名
            $fileName = $path.$size.'.png';
            \QRcode::png($data, false, $level, $size);


    }

    /**
     * 验证码
     */
    public function verify() {
        //验证码类型
        $type = I('get.type') ? I('get.type') : 'index_index';
//        $fontSize = I('get.fontSize') ? I('get.fontSize') : '20';
//        $length = I('get.length') ? I('get.length') : '4';

        $config = array(
            'fontSize' => 15, // 验证码字体大小(px)
            'length' => 4, // 验证码位数
            'imageH' => 40, // 验证码图片高度
            'imageW' => 113, // 验证码图片宽度
            'fontttf' => '4.ttf', // 验证码字体，不设置随机获取
            'useCurve' => false, // 是否画混淆曲线
            'useNoise' => false, // 是否添加杂点	 true
        );
        $Verify = new Verify($config);
        $Verify->entry($type);
    }

    // 促销活动页面
    public function promoteList() {
        $Model = new \Think\Model();
        $goodsList = $Model->query("select * from __PREFIX__goods as g inner join __PREFIX__flash_sale as f on g.goods_id = f.goods_id   where " . time() . " > start_time  and " . time() . " < end_time");
        $brandList = M('brand')->getField("id,name,logo");
        $this->assign('brandList', $brandList);
        $this->assign('goodsList', $goodsList);
        $this->display();
    }

    function truncate_tables() {
        $model = new \Think\Model(); // 实例化一个model对象 没有对应任何数据表
        $tables = $model->query("show tables");
        $table = array('tp_admin', 'tp_config', 'tp_region', 'tp_system_module', 'tp_admin_role', 'tp_system_menu');
        foreach ($tables as $key => $val) {
            if (!in_array($val['tables_in_tpshop'], $table))
                echo "truncate table " . $val['tables_in_tpshop'] . ' ; ';   
        }
    }

}
